# -*- coding: utf-8 -*-

# Copyright (C) 2009 emijrp
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import re, urllib, sys, time
import wikipedia, catlib, pagegenerators

def saveNumbers(ediciones, tipo):
    """ Guarda el número de ediciones en un fichero """
    if ediciones==0:
        if tipo=='c':
            f = open('zzcrredmay_created.txt')
        elif tipo=='e':
            f = open('zzcrredmay_existed.txt')
        elif tipo=='t':
            f = open('zzcrredmay_total.txt')

        return int(f.read())
    
    else:
        if tipo=='c':
            f = open('zzcrredmay_created.txt', 'w')
        elif tipo=='e':
            f = open('zzcrredmay_existed.txt', 'w')
        elif tipo=='t':
            f = open('zzcrredmay_total.txt', 'w')
        f.write(str(ediciones))

    f.close()

for arg in wikipedia.handleArgs():
    if arg.startswith('-start'):
            if len(arg) == 6:
                st = wikipedia.input(
                                 u'Which page do you want to change?')
            else:
                st = arg[7:]
            source = 'allpages'

stat_created = saveNumbers(0, 'c') #number of created redirects
stat_existed = saveNumbers(0, 'e') #redirect already existed
stat_total   = saveNumbers(0, 't') #total parsed pages

if len(sys.argv)>=2:
    st=sys.argv[1]

gen=pagegenerators.AllpagesPageGenerator(start = st, namespace = 0, includeredirects = False, site = wikipedia.Site('es', 'wikipedia'))
pre=pagegenerators.PreloadingGenerator(gen, pageNumber=250, lookahead=250)

c=0
t1=time.time()

for page in pre:
        wtitle=page.title()
        stat_total += 1

        if (stat_total % 250 == 0):
            wikipedia.output(u'\03{lightgreen}  Status: working on \03{lightblue}%s\03{default}.\n  \03{lightyellow}%s\03{default} pages created, \03{lightyellow}%s\03{default} already existed, \03{lightyellow}%s\03{default} pages parsed.\03{default}' % (wtitle, stat_created, stat_existed, stat_total))
            saveNumbers(stat_created, 'c')
            saveNumbers(stat_existed, 'e')
            saveNumbers(stat_total, 't')

        if not page.exists() or page.isRedirectPage() or page.isDisambig():
                continue
        else:
                if re.search(ur"[^a-zA-Z ]", wtitle):
                        continue
                elif len(wtitle.split(" "))>=3:
                        trozos=wtitle.split(" ")
                        min=may=False
                        
                        for i in trozos[1:]:
                                imay=i.upper()
                                imin=i.lower()
                                if imay[0]==i[0]:#primer caracter comprobar
                                        may=True
                                if imin[0]==i[0]:
                                        min=True
                        
                        if min and may:
                                #crear redirect con todo en minusculas
                                wiii=wikipedia.Page(ensite, wtitle.lower())
                                if not wiii.exists():
                                        if c>=10:
                                                while time.time()-t1<60:
                                                        time.sleep(0.1)
                                                t1=time.time()
                                                c=0
                                        c+=1
                                        wiii.put(u"#REDIRECCIÓN [[%s]]" % wtitle, u"Bot: Creando redirección a [[%s]]" % wtitle)
                                        stat_created += 1
                                else:
                                        wikipedia.output(u"Ya existe el redirect a %s" % wtitle)
                                        stat_existed += 1
